<template>
    <div class="exam-question-list">
        <el-card>
            <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center">
                <el-select v-model="type" placeholder="题型筛选" style="width: 150px">
                    <el-option label="全部" value="" />
                    <el-option label="单选" value="single" />
                    <el-option label="多选" value="multi" />
                    <el-option label="判断" value="judge" />
                    <el-option label="填空" value="blank" />
                    <el-option label="简答" value="short" />
                </el-select>
                <el-input v-model="search" placeholder="搜索题干/选项/解析" clearable style="width: 320px" @keyup.enter="getList" />
                <el-button type="primary" @click="getList">搜索</el-button>
                <el-button type="primary" @click="openAdd">新增题目</el-button>
            </div>
            <el-table :data="list" style="width: 100%">
                <el-table-column prop="id" label="ID" width="60" />
                <el-table-column prop="type" label="题型" width="80">
                    <template #default="scope">
                        <span>{{ typeMap[scope.row.type] || scope.row.type }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="content" label="题干" />
                <el-table-column prop="score" label="分值" width="60" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="del(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="page"
                :page-size="20"
                :total="total"
                layout="total, prev, pager, next"
                @current-change="getList"
                style="margin-top: 16px"
            />
        </el-card>
        <el-dialog v-model="showForm" :title="form.id ? '编辑题目' : '新增题目'">
            <el-form :model="form" label-width="80px">
                <el-form-item label="题型">
                    <el-select v-model="form.type" placeholder="请选择题型">
                        <el-option label="单选" value="single" />
                        <el-option label="多选" value="multi" />
                        <el-option label="判断" value="judge" />
                        <el-option label="填空" value="blank" />
                        <el-option label="简答" value="short" />
                    </el-select>
                </el-form-item>
                <el-form-item label="题干">
                    <el-input v-model="form.content" type="textarea" />
                </el-form-item>
                <el-form-item label="选项" v-if="form.type === 'single' || form.type === 'multi'">
                    <div v-for="(opt, idx) in form.options" :key="idx" style="display: flex; align-items: center; margin-bottom: 8px">
                        <div style="width: 40px; text-align: center; margin-right: 8px; font-weight: 600">{{ String.fromCharCode(65 + idx) }}</div>
                        <el-input v-model="form.options[idx]" style="flex: 1" />
                        <el-button type="text" @click="removeOption(idx)" style="margin-left: 8px; color: #f56c6c">移除</el-button>
                    </div>
                    <el-button type="primary" plain @click="addOption">添加选项</el-button>
                </el-form-item>
                <el-form-item label="选项" v-if="form.type === 'judge'">
                    <el-input v-model="form.options[0]" disabled style="margin-bottom: 8px" />
                    <el-input v-model="form.options[1]" disabled />
                </el-form-item>
                <el-form-item label="答案">
                    <div class="full-width" v-if="form.type === 'single'">
                        <el-select v-model="form.answer" placeholder="请选择正确答案">
                            <el-option
                                v-for="(opt, idx) in form.options"
                                :key="idx"
                                :label="String.fromCharCode(65 + idx) + ' ' + opt"
                                :value="String.fromCharCode(65 + idx)"
                            />
                        </el-select>
                    </div>
                    <div v-else-if="form.type === 'multi'">
                        <el-checkbox-group v-model="form.answer">
                            <el-checkbox v-for="(opt, idx) in form.options" :key="idx" :label="String.fromCharCode(65 + idx)">
                                {{ String.fromCharCode(65 + idx) + ' ' + opt }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else-if="form.type === 'judge'">
                        <el-radio-group v-model="form.answer">
                            <el-radio :label="'A'">对</el-radio>
                            <el-radio :label="'B'">错</el-radio>
                        </el-radio-group>
                    </div>
                    <div v-else>
                        <el-input v-model="form.answer" type="textarea" placeholder="填空或简答题请直接填写答案文本" />
                    </div>
                </el-form-item>
                <el-form-item label="分值">
                    <el-input-number v-model="form.score" :min="1" />
                </el-form-item>
                <el-form-item label="解析">
                    <el-input v-model="form.analysis" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showForm = false">取消</el-button>
                <el-button type="primary" @click="submit">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '/@/utils/request'

const type = ref('')
const search = ref('')
const page = ref(1)
const total = ref(0)
const list = ref([])
const showForm = ref(false)
const form = reactive({ id: 0, type: '', content: '', options: [], answer: '', score: 1, analysis: '' })
const typeMap = { single: '单选', multi: '多选', judge: '判断', blank: '填空', short: '简答' }

function getList() {
    request.get('/admin/examQuestion/index', { type: type.value, page: page.value, search: search.value }).then((res) => {
        if (res.code === 1) {
            list.value = res.data.data
            total.value = res.data.total
        }
    })
}
function openAdd() {
    Object.assign(form, { id: 0, type: '', content: '', options: [], answer: '', score: 1, analysis: '' })
    showForm.value = true
}
function openEdit(row) {
    Object.assign(form, row)
    // ensure options is array
    if (!form.options) form.options = []
    // if options is a JSON string, parse it; if it's an object keyed by letters, convert to values array
    if (typeof form.options === 'string') {
        try {
            const parsed = JSON.parse(form.options)
            form.options = parsed
        } catch {
            form.options = []
        }
    }
    if (form.options && typeof form.options === 'object' && !Array.isArray(form.options)) {
        // object keyed by letters => convert to array of texts for editing inputs
        form.options = Object.values(form.options)
    }
    // if empty and judge, set default
    if (form.type === 'judge' && (!form.options || !form.options.length)) form.options = ['对', '错']
    // answer may be stored as JSON string
    if (typeof form.answer === 'string') {
        try {
            const a = JSON.parse(form.answer)
            form.answer = a
        } catch {
            // keep as string
        }
    }
    // if stored as comma list (e.g. "A,B,C") convert to array for multi
    if (typeof form.answer === 'string' && form.answer.indexOf(',') !== -1) {
        form.answer = form.answer.split(',').map((s) => s.trim())
    }
    // if it's array with single element but current type is single, use single value
    if (Array.isArray(form.answer) && form.type === 'single') {
        form.answer = form.answer[0] || ''
    }
    showForm.value = true
}
function submit() {
    let data = { ...form }
    // validate options
    if (data.type === 'single' || data.type === 'multi') {
        if (!Array.isArray(data.options) || data.options.length < 2) {
            ElMessage.error('请选择或添加至少两个选项')
            return
        }
    }
    if (data.type === 'judge') {
        // save judge options as key-value A/B (send as object so backend model casts to JSON)
        const judgeObj = { A: '对', B: '错' }
        data.options = judgeObj
        // store judge as letter A/B
        if (!data.answer) data.answer = 'A'
    }
    // normalize answer for multi -> array
    if (data.type === 'multi') {
        if (!Array.isArray(data.answer) && data.answer) data.answer = [data.answer]
        // save multi as comma-separated letters
        if (Array.isArray(data.answer)) data.answer = data.answer.join(',')
    }

    // For single/multi/judge, convert options to key-value mapping A: text before submit
    if (data.type === 'single' || data.type === 'multi') {
        if (Array.isArray(data.options)) {
            const obj = {}
            data.options.forEach((t, i) => {
                const k = String.fromCharCode(65 + i)
                obj[k] = t
            })
            // send as object; the backend model will JSON-encode it
            data.options = obj
        }
    }
    let url = data.id ? '/admin/examQuestion/edit/' + data.id : '/admin/examQuestion/add'
    request.post(url, data).then((res) => {
        if (res.code === 1) {
            ElMessage.success(res.msg)
            showForm.value = false
            getList()
        } else {
            ElMessage.error(res.msg)
        }
    })
}
function addOption() {
    form.options.push('')
}
function removeOption(idx) {
    form.options.splice(idx, 1)
}

// 当用户切换题型为判断题时，自动填充默认选项
watch(
    () => form.type,
    (val) => {
        if (val === 'judge') {
            form.options = ['对', '错']
            if (!form.answer) form.answer = 'A'
        } else if (val === 'single' || val === 'multi') {
            if (!Array.isArray(form.options)) form.options = []
            if (val === 'multi') {
                // ensure checkbox group v-model is an array so checkboxes can be toggled
                if (!Array.isArray(form.answer)) form.answer = []
            } else if (val === 'single') {
                // if switching from multi to single, normalize to single value
                if (Array.isArray(form.answer)) form.answer = form.answer[0] || ''
            }
        }
    }
)
function del(id) {
    ElMessageBox.confirm('确定删除该题目？', '提示', { type: 'warning' }).then(() => {
        request.post('/admin/examQuestion/delete/' + id).then((res) => {
            if (res.code === 1) {
                ElMessage.success(res.msg)
                getList()
            } else {
                ElMessage.error(res.msg)
            }
        })
    })
}
onMounted(getList)
</script>

<style scoped>
.exam-question-list {
    max-width: 900px;
    margin: 0 auto;
}
.full-width {
    width: 100%;
    display: block;
}
</style>
